#!/usr/bin/env node
/**
 * 测试中文搜索功能（无需外部服务）
 */

async function testSearchLogic() {
  console.log('测试中文搜索逻辑');
  console.log('================\n');
  
  // 模拟 front-matter 数据
  const testData = {
    "标题": "人工智能技术指南",
    "分类": "技术",
    "标签": ["AI", "机器学习", "深度学习", "人工智能"],
    "作者": "技术团队",
    "创建时间": "2025-01-25",
    "难度": "中级",
    "状态": "已发布",
    "关键词": ["神经网络", "自然语言处理", "计算机视觉"]
  };
  
  // 复制搜索逻辑方法
  function parseSearchTerms(keywords) {
    const terms = [];
    const normalizedKeywords = keywords.toLowerCase().trim();
    const spaceSeparated = normalizedKeywords.split(/\s+/).filter(term => term.length > 0);
    
    for (const term of spaceSeparated) {
      if (containsChinese(term)) {
        terms.push(term);
        if (term.length > 1) {
          for (let i = 0; i < term.length; i++) {
            const char = term.charAt(i);
            if (isChinese(char) && !terms.includes(char)) {
              terms.push(char);
            }
          }
        }
      } else {
        terms.push(term);
      }
    }
    return terms.filter(term => term.length > 0);
  }
  
  function containsChinese(text) {
    return /[\u4e00-\u9fff]/.test(text);
  }
  
  function isChinese(char) {
    return /[\u4e00-\u9fff]/.test(char);
  }
  
  function flattenFrontMatter(obj, prefix = '') {
    let result = '';
    for (const [key, value] of Object.entries(obj)) {
      const currentKey = prefix ? `${prefix}.${key}` : key;
      if (value === null || value === undefined) continue;
      
      if (typeof value === 'object' && !Array.isArray(value)) {
        result += flattenFrontMatter(value, currentKey) + ' ';
      } else if (Array.isArray(value)) {
        result += `${currentKey}: ${value.join(' ')} `;
      } else {
        result += `${currentKey}: ${value} `;
      }
    }
    return result;
  }
  
  function matchesKeywords(frontMatter, searchTerms) {
    const searchableText = flattenFrontMatter(frontMatter).toLowerCase();
    const chineseTerms = searchTerms.filter(term => containsChinese(term));
    const englishTerms = searchTerms.filter(term => !containsChinese(term));
    
    let chineseMatch = chineseTerms.length === 0;
    let englishMatch = englishTerms.length === 0;
    
    if (chineseTerms.length > 0) {
      chineseMatch = chineseTerms.some(term => searchableText.includes(term));
    }
    
    if (englishTerms.length > 0) {
      englishMatch = englishTerms.every(term => searchableText.includes(term));
    }
    
    return chineseMatch && englishMatch;
  }
  
  // 测试数据
  const testQueries = [
    '人工智能',
    '技术',
    'AI',
    '机器学习',
    'AI 技术',
    '人工 智能',
    '深度学习',
    '神经网络',
    '计算机视觉',
    '中级',
    '已发布'
  ];
  
  console.log('扁平化后的搜索文本:');
  const flatText = flattenFrontMatter(testData);
  console.log(flatText);
  console.log('');
  
  console.log('搜索测试结果:');
  console.log('=============');
  
  for (const query of testQueries) {
    const terms = parseSearchTerms(query);
    const matches = matchesKeywords(testData, terms);
    
    console.log(`查询: "${query}"`);
    console.log(`  解析词汇: [${terms.join(', ')}]`);
    console.log(`  匹配结果: ${matches ? '✅ 匹配' : '❌ 不匹配'}`);
    console.log('');
  }
  
  console.log('🎉 中文搜索逻辑测试完成！');
}

testSearchLogic().catch(console.error);
